﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Security.Cryptography;
using University.Workshop.Model;
using University.Workshop.DataAccess;
using System.IO;

namespace University.Workshop.Business
{
    public class TripleDesManager
    {
        public TripleDESUtil des = new TripleDESUtil();

        public TripleDESUtil Encriptar(string cadenaOrigen)
        {
            
            UTF8Encoding encoding = new UTF8Encoding();

            byte[] message = encoding.GetBytes(cadenaOrigen);



            TripleDESCryptoServiceProvider criptoProvider =

                new TripleDESCryptoServiceProvider();



            des.IV = criptoProvider.IV;

            des.Key = criptoProvider.Key;



            ICryptoTransform criptoTransform =

                criptoProvider.CreateEncryptor(des.Key, des.IV);



            MemoryStream memoryStream = new MemoryStream();



            CryptoStream cryptoStream =

                new CryptoStream(memoryStream,

                         criptoTransform,

                         CryptoStreamMode.Write);



            cryptoStream.Write(message, 0, message.Length);

            // cryptoStream.Flush();

            cryptoStream.FlushFinalBlock();



            byte[] encriptado = memoryStream.ToArray();



            //string cadenaEncriptada = encoding.GetString(encriptado);

            //Console.WriteLine("Texto encriptado {0}", cadenaEncriptada);


            // Guardar Los Tres en la Base de DAtos! 

            this.des.Encriptado = encriptado;
            return des;

        }
        public string DesEncriptar(byte[] message, TripleDESUtil Des1)
        {

            TripleDES cryptoProvider =

                new TripleDESCryptoServiceProvider();



            ICryptoTransform cryptoTransform =

                cryptoProvider.CreateDecryptor(Des1.Key,Des1.IV);



            MemoryStream memoryStream = new MemoryStream(message);



            CryptoStream cryptoStream =

                new CryptoStream(memoryStream,

                         cryptoTransform,

                         CryptoStreamMode.Read);




            StreamReader sr = new StreamReader(cryptoStream, true);



            string textoLimpio = sr.ReadToEnd();

            //Console.WriteLine("Texto Limpio:{0}", textoLimpio);



            return textoLimpio;

        }
    }
}
